//
//  PersonalPageViewController.swift
//  FeastBooking
//
//  Created by Imon on 2017/7/6.
//  Copyright © 2017年 Imon. All rights reserved.
//

import UIKit
import RxSwift

class PersonalPageViewController: UIViewController {    
    
    var userProfile: UserProfile?
    
    var scrollView: UIScrollView?
    
    var summaryRect: CGRect?
    
    var headerView: UIView?
    
    let authManager = AuthManager.share
    
    var cashbackVM: CashBackViewModel?
    
    var userProfileVM: UserProfileViewModel?
    
    let disposeBag = DisposeBag()
    
    var token: String?
    
    let imageView: UIImageView = {
        let imageView = UIImageView()
        imageView.contentMode = .scaleAspectFill
        imageView.image = UIImage(named: "background")
        imageView.layer.masksToBounds = true
        return imageView
    }()
    
    let messageButton: UIButton = {
        let button = UIButton()
        button.setImage(UIImage(named: "message"), for: .normal)
        return button
    }()
    
    let avatarPH = UIImage(named: "placeholder")
    
    let avatar: UIImageView = {
        let imageView = UIImageView()
        imageView.layer.cornerRadius = avatarRadius
        imageView.layer.borderWidth = 2
        imageView.layer.borderColor = UIColor.white.cgColor
        imageView.layer.masksToBounds = true
        imageView.contentMode = .scaleAspectFill
        imageView.image = UIImage(named: "placeholder")
        return imageView
    }()
    
    let nameLabel: UILabel = {
        let label = UILabel()
        label.textColor = UIColor.black
        label.font = AppFont(size: 14)
        label.text = ""
        return label
    }()
    
    let emailLabel: UILabel = {
        let label = UILabel()
        label.textColor = UIColor.gray
        label.font = AppFont(size: 13)
        label.text = ""
        return label
    }()
    
    
    let pointer: UIImageView = {
        let imageView = UIImageView()
        imageView.contentMode = .scaleAspectFit
        imageView.image = UIImage(named: "pointer")
        return imageView
    }()
    
    let cashback: CashBackMenu = {
        let cb = CashBackMenu()
        return cb
    }()
    
    let orders: PersonMenu = {
        let menu = PersonMenu()
        menu.titleLabel.text = LanguageHelper.getString(key: "PROCESSING_ORDER")
        return menu
    }()
    
    let historyOrder: PersonMenu = {
        let menu = PersonMenu()
        menu.titleLabel.text = LanguageHelper.getString(key: "HISTORY_ORDER")
        return menu
    }()
    
    let myFavorite: PersonMenu = {
        let menu = PersonMenu()
        menu.titleLabel.text = LanguageHelper.getString(key: "MY_FAVOURITE")
        return menu
    }()
    
    let commonIssue: PersonMenu = {
        let menu = PersonMenu()
        menu.titleLabel.text = LanguageHelper.getString(key: "COMMON_ISSUE")
        return menu
    }()
    
    let setting: PersonMenu = {
        let menu = PersonMenu()
        menu.titleLabel.text = LanguageHelper.getString(key: "SETTING")
        return menu
    }()
    
    let redPoint: UIView = {
        let view = UIView()
        view.backgroundColor = redPointColor
        return view
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = lightSaperatorColor
        
        headerView = UIView()
        headerView?.frame = CGRect(x: 0, y: 0, width: self.view.bounds.width, height: headerHeight)
        imageView.frame = (headerView?.bounds)!
        headerView?.addSubview(imageView)
        scrollView = UIScrollView()
        scrollView?.frame = self.view.bounds
        scrollView?.showsVerticalScrollIndicator = false
        scrollView?.showsHorizontalScrollIndicator = false
        scrollView?.isScrollEnabled = true
        scrollView?.alwaysBounceVertical = true
        scrollView?.delegate = self
        scrollView?.autoresizingMask = UIViewAutoresizing.flexibleHeight
        let messageWidth: CGFloat = 25
        messageButton.frame = CGRect(x: self.view.bounds.width - messageWidth - 15, y: 35, width: 25, height: 25)
        messageButton.addTarget(self, action: #selector(showMessageView(_:)), for: .touchUpInside)
        headerView?.addSubview(messageButton)
        
        summaryRect = CGRect(x: 0, y: 70, width: self.view.bounds.width, height: headerHeight - 70)
        let actionView = UIView()
        actionView.frame = summaryRect!
        
        layoutUserProfile()
        headerView?.addSubview(avatar)
        headerView?.addSubview(nameLabel)
        headerView?.addSubview(emailLabel)
        headerView?.addSubview(pointer)
        scrollView?.addSubview(headerView!)
        cashback.frame = CGRect(x: 0, y: headerHeight, width: self.view.bounds.width, height: cashbackHeight)
        scrollView?.addSubview(cashback)
        
        let gapWithCB: CGFloat = 25
        orders.frame = CGRect(x: 0, y: headerHeight + cashbackHeight + gapWithCB , width: self.view.bounds.width, height: menuHeight)
        historyOrder.frame = CGRect(x: 0, y: headerHeight + cashbackHeight + gapWithCB + menuGap + menuHeight , width: self.view.bounds.width, height: menuHeight)
        myFavorite.frame = CGRect(x: 0, y: headerHeight + cashbackHeight + gapWithCB + menuGap * 2 + menuHeight * 2 , width: self.view.bounds.width, height: menuHeight)
        commonIssue.frame = CGRect(x: 0, y: headerHeight + cashbackHeight + gapWithCB + menuGap * 3 + menuHeight * 3 , width: self.view.bounds.width, height: menuHeight)
        setting.frame = CGRect(x: 0, y: headerHeight + cashbackHeight + gapWithCB + menuGap * 4 + menuHeight * 4 , width: self.view.bounds.width, height: menuHeight)
        //setting.frame = CGRect(x: 0, y: headerHeight + menuGap * 4 + menuHeight * 3 , width: self.view.bounds.width, height: menuHeight)
        
        
        let orderTapGR = UITapGestureRecognizer()
        orderTapGR.addTarget(self, action: #selector(showProcessingOrders(_:)))
        orders.addGestureRecognizer(orderTapGR)
        
        let historyTapGR = UITapGestureRecognizer()
        historyTapGR.addTarget(self, action: #selector(showHistoryOrders(_:)))
        historyOrder.addGestureRecognizer(historyTapGR)
        
        let favouriteTapGR = UITapGestureRecognizer()
        favouriteTapGR.addTarget(self, action: #selector(showFavourites(_:)))
        myFavorite.addGestureRecognizer(favouriteTapGR)
        
        let settingTapGR = UITapGestureRecognizer()
        settingTapGR.addTarget(self, action: #selector(showSettingView(_:)))
        setting.addGestureRecognizer(settingTapGR)
        
        let helpingTapGR = UITapGestureRecognizer()
        helpingTapGR.addTarget(self, action: #selector(showHelpingView(_:)))
        commonIssue.addGestureRecognizer(helpingTapGR)
        
        scrollView?.addSubview(orders)
        scrollView?.addSubview(historyOrder)
        scrollView?.addSubview(myFavorite)
        scrollView?.addSubview(commonIssue)
        scrollView?.addSubview(setting)
        scrollView?.contentSize = CGSize(width: self.view.bounds.width, height: setting.frame.origin.y + setting.frame.height)
        
        let gestureR = UITapGestureRecognizer()
        gestureR.addTarget(self, action: #selector(tapPersonalInformation(_:)))
        
        headerView?.addSubview(actionView)
        actionView.addGestureRecognizer(gestureR)
        actionView.isUserInteractionEnabled = true
        
        let redPointSize: CGFloat = 8
        redPoint.frame = CGRect(x: messageButton.frame.origin.x + messageButton.frame.width - redPointSize / 2, y: messageButton.frame.origin.y, width: redPointSize, height: redPointSize)
        redPoint.layer.cornerRadius = redPointSize / 2
        redPoint.layer.masksToBounds = true
        
        self.view.addSubview(scrollView!)
        
        NotificationCenter.default.addObserver(self, selector: #selector(hasNewMsg), name: hasNewUnReadMsg, object: nil)
    }
    
    func layoutUserProfile() {
        let avatarLeading: CGFloat = 15
        avatar.frame = CGRect(x: avatarLeading, y: (summaryRect?.origin.y)! + (summaryRect?.height)! - 20 - avatarRadius * 2, width: avatarRadius * 2, height: avatarRadius * 2)
        let textMaxSize = CGSize(width: self.view.bounds.width - avatarLeading - avatar.frame.width - 5 - 30, height: 20)
        let nameWidth = TextSize.textSize(text: nameLabel.text!, font: AppFont(size: 14), maxSize: textMaxSize).width
        let idWidth = TextSize.textSize(text: emailLabel.text!, font: AppFont(size: 13), maxSize: textMaxSize).width
        nameLabel.frame = CGRect(x: avatarLeading + avatar.frame.width + 10, y: avatar.frame.origin.y + 10, width: nameWidth, height: 15)
        emailLabel.frame = CGRect(x: avatarLeading + avatar.frame.width + 10, y: avatar.frame.origin.y + 10 + nameLabel.frame.height + 3, width: idWidth, height: 15)
        pointer.frame = CGRect(x: self.view.bounds.width - 30, y: avatar.frame.origin.y + avatarRadius - 15 / 2, width: 20, height: 20)
    }
    
    func showMessageView(_ sender: UIButton) {
        let messageView = UIStoryboard(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "MessageViewController") as! MessageViewController
        messageView.hidesBottomBarWhenPushed = true
        self.navigationController?.pushViewController(messageView, animated: true)
    }
    
    func updateBadge() {
        if hasUnreadMsg {
            navigationController?.tabBarItem.badgeValue = ""
        } else {
            navigationController?.tabBarItem.badgeValue = nil
        }
    }
    
    func setUserInfo() {
        initVM()
        if let vm = cashbackVM {
            vm.getUserCashBack().subscribe(onNext: { [unowned self] cashBackRes in
                if cashBackRes.userId != nil {                    
                    self.cashback.initValue(userCashback: cashBackRes)
                }
            })
            .addDisposableTo(disposeBag)
        }
        if let vm = userProfileVM {
            vm.getProfile().subscribe(onNext: { [unowned self] profile in
                if profile.userId != nil {
                    if let avatarUrl = profile.avatar {
                        let url = URL(string: avatarUrl)!
                        self.avatar.kf.setImage(with: url, placeholder: self.avatarPH)
                    }
                    self.nameLabel.text = profile.username != nil ? profile.username! : ""
                    self.emailLabel.text = profile.email != nil ? "\(profile.email!)" : ""
                    self.layoutUserProfile()
                    self.userProfile = profile
                }
            })
            .addDisposableTo(disposeBag)
        }
    }
    
    func initVM() {
        let authManager = AuthManager.share
        if authManager.hasLogined() {
            if let token = authManager.getToken() as? String {
                cashbackVM = CashBackViewModel(token: token)
                userProfileVM = UserProfileViewModel(token: token)
            }
        }
    }
    
    func checkLoginStatus() {
        if authManager.hasLogined() {
            self.token = (authManager.getToken() as! String)
        } else {
            self.token = nil
        }
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    func tapPersonalInformation(_ sender: UITapGestureRecognizer) {
        if token == nil {
            showLoginPage()
        } else {
            self.performSegue(withIdentifier: "showPersonalDetail", sender: nil)
        }
    }
    
    func showProcessingOrders(_ sender: UITapGestureRecognizer) {
        UIView.animate(withDuration: 0.3, animations: { [unowned self] in
            self.orders.backgroundColor = UIColor.init(red: 200 / 255.0, green: 200 / 255.0, blue: 200 / 255.0, alpha: 0.5)
            }, completion: { [unowned self] bool in
                self.orders.backgroundColor = UIColor.white
                self.performSegue(withIdentifier: "showProcessingOrders", sender: nil)
        })
    }
    
    func showHistoryOrders(_ sender: UITapGestureRecognizer) {
        UIView.animate(withDuration: 0.3, animations: { [unowned self] in
            self.historyOrder.backgroundColor = UIColor.init(red: 200 / 255.0, green: 200 / 255.0, blue: 200 / 255.0, alpha: 0.5)
            }, completion: { [unowned self] bool in
                self.historyOrder.backgroundColor = UIColor.white
                self.performSegue(withIdentifier: "showHistoryOrders", sender: nil)
        })
    }
    
    func showFavourites(_ sender: UITapGestureRecognizer) {
        UIView.animate(withDuration: 0.3, animations: { [unowned self] in
            self.myFavorite.backgroundColor = UIColor.init(red: 200 / 255.0, green: 200 / 255.0, blue: 200 / 255.0, alpha: 0.5)
            }, completion: { [unowned self] bool in
                self.myFavorite.backgroundColor = UIColor.white
                self.performSegue(withIdentifier: "showFavourite", sender: nil)
        })
    }
    
    func showSettingView(_ sender: UITapGestureRecognizer) {
        UIView.animate(withDuration: 0.3, animations: { [unowned self] in
            self.setting.backgroundColor = UIColor.init(red: 200 / 255.0, green: 200 / 255.0, blue: 200 / 255.0, alpha: 0.5)
            }, completion: { [unowned self] bool in
                self.setting.backgroundColor = UIColor.white
                let settingView = UIStoryboard(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "SettingViewController") as! SettingViewController
                settingView.hidesBottomBarWhenPushed = true
                settingView.logoutCompletion = { [unowned self] in
                    let tabVC = self.tabBarController as! EntryTabBarController
                    tabVC.selectedIndex = 0
                }
                self.navigationController?.pushViewController(settingView, animated: true)
        })
    }
    
    func showHelpingView(_ sender: UITapGestureRecognizer) {
        UIView.animate(withDuration: 0.3, animations: { [unowned self] in
            self.commonIssue.backgroundColor = UIColor.init(red: 200 / 255.0, green: 200 / 255.0, blue: 200 / 255.0, alpha: 0.5)
            }, completion: { [unowned self] bool in
                self.commonIssue.backgroundColor = UIColor.white
                let helpingView = UIStoryboard(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "HelpingViewController") as! HelpingViewController
                helpingView.hidesBottomBarWhenPushed = true
                self.navigationController?.pushViewController(helpingView, animated: true)
        })
    }
    
    func checkUnreadMsg() {
        if let db = SystemMessageDB.getShareInstance() {
            let count = db.unreadCount()
            if count > 0 {
                self.headerView!.addSubview(redPoint)
            } else {
                redPoint.removeFromSuperview()
                NotificationCenter.default.post(name: hasReadAllMsgs, object: nil)
            }
        }
    }
    
    func hasNewMsg() {
        self.headerView!.addSubview(redPoint)
    }
    
    override func viewWillAppear(_ animated: Bool) {
        self.navigationController?.setNavigationBarHidden(true, animated: false)
        checkLoginStatus()
        setUserInfo()
        checkUnreadMsg()
        if LATESTVERSION > APPVERSION {
            setting.showRedPoint()
        } else {
            setting.hideRedPoint()
        }
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        self.navigationController?.setNavigationBarHidden(false, animated: false)
    }
    
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        let v1 = segue.destination
        v1.hidesBottomBarWhenPushed = true
        if segue.identifier == "showPersonalDetail" {
            let view = segue.destination as! PersonalDetailPageViewController
            view.token = self.token
            view.userProfile = self.userProfile
            view.logoutCompletion = { [unowned self] in
                let tabVC = self.tabBarController as! EntryTabBarController
                tabVC.selectedIndex = 0
            }
        }
    }
    
    
}

extension PersonalPageViewController: UIScrollViewDelegate {
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
        let y = scrollView.contentOffset.y;
        
        var imgViewF = self.imageView.frame;
        
        //放大图片处理
        
        //监听到scrollView向下滚动时,改变图片的Frame,达到放大图片的效果
        
        if y < 0 {
            
            imgViewF.origin.y =  y;
            
            imgViewF.origin.x =  y;
            
            imgViewF.size.height = headerHeight - y;
            
            imgViewF.size.width = UIScreen.main.bounds.width - y;
            
            self.imageView.frame = imgViewF;
            
        }
        
    }
    
}
